import datetime
from flask import Blueprint,request,jsonify
from flask.json import JSONEncoder
import requests

from views.db import Db

import json

from utils.jwtc import myjwt

from utils.Make_password import make_password

from utils.myfile import MyFile

from utils.redis import rs

from utils.acl import ACL

import redis

import re

from views.db import db

from utils.acl import  acl

from utils.myfile import get_data

import time

import functools

bp_user = Blueprint("user",__name__)



@bp_user.route('/loginM',methods = ['POST','GET'])
def loginM():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        print(data)
        # sql = """select * from user where username = '%s'"""%(data['username'])
        # res = db.get_one(sql)
        # 用户账号密码
        sql = " select * from user where username='%s' and password='%s' " % (data['username'],data['password'])

        res = db.get_one(sql)
        
        print(sql)
        print(res)
        if res:
            if res['password'] == data['password']:
                uid = res['id']
                username = res['username']
                is_admin = res['is_admin']
                token = myjwt.encode_jwt({'data':{'uid':res['id']}})

                if res['is_admin']:

                    return jsonify({'code':200,"mes":"登陆成功","token":token,'uid':uid,'username':username,'is_admin':is_admin,"url":[]})

                ress = acl.get_vue(uid)
                # 把url存入redis,
                rs.insert_set('users'+str(uid),ress)
                aa = rs.find_set('users'+str(uid))
                print(aa)

                
                   
                return jsonify({'code':200,"mes":"登陆成功","token":token,'uid':uid,'username':username,'is_admin':is_admin,"url":aa})

                
            else:
                return jsonify({'code': 20021, "mes": "密码错误"})
        else:
            return jsonify({'code': 20021,"mes":"账户不存在"})

#构建2层分类
def getresdata(data):
    # 把顶级拿出来放到列表中
    list = []
    idlist=[]
    for i in data:
        id = i['pid']
        if id not in idlist:
            list.append({'id':id,'name':i['pname'],'son':[]})
            idlist.append(id)
    # 变理顶级列表，在遍历数据，把子类加到顶级列表
    for j,value in enumerate(list):

        for i in data:
        
            if value['id'] == i['pid']:
                
                list[j]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
    return list



@bp_user.route('/getResource')

def getResource():

    uid = 1

    res = acl.get_resourcelist(uid,1) 

    mes = getresdata(res)

    # id = request.args.get('id')

    # is_admin = request.args.get('is_admin')
    # if is_admin:
    #     sql = "select * from resource where type = 1"
    #     res = db.get_all(sql)
    
    # else:
    #     res = acl.get_resourcelist(id,1)
    # mes = getattr(res)

    return jsonify({'list':mes})


# 角色列表
@bp_user.route('/rolelist')
def rolelist():

    sql = " select * from role "

    res = db.get_all(sql)

    return jsonify({"code":200,"list":res})

# 资源列表
@bp_user.route('/resourcelist')
def resourcelist():

    id = request.args.get('id')
    if id:
        sql = 'select resourceid from role_resource where roleid={}'.format(id)
        res = db.get_all(sql)
        list = []
        for i in res:
            list.append(i['resourceid'])
    else:
        time.sleep(1)
        sql = 'select * from resource'
        list = db.get_all(sql)
    return jsonify({'code':200,'list':list})


# 配置资源接口
@bp_user.route('/setrole',methods=['GET','POST'])
def setrole():
    if request.method == 'POST':
        data = get_data()
        # 先删除已有的资源
        id = request.args.get('id')
        sql = 'delete from role_resource where roleid={}'.format(int(id))
        db.update(sql)
        # 配置新的资源
        ids = []
        for i in data:
            ids.append(i)
        for i in ids:
            sql1 = 'insert into role_resource(roleid,resourceid) values({},{})'.format(int(id),i)
            db.update(sql1)
        return jsonify({'code':200,'msg':'配置成功'})

@bp_user.route('/ggg')
def ggg():
    uid = 2
    res = acl.get_interface_reslist(uid)
    return jsonify({'list':res})
 

@bp_user.route('/getresource_pid',methods=['GET','POST'])
def getresource_pid():

    if request.method == 'POST':
        id = request.args.get('pid')
        time.sleep(1)
        sql = "select r.id,r.name as roname from resource as r left join role_resource as rr on r.id=rr.resourceid where rr.roleid=%d" % (int(id))
        res = db.get_all(sql)
        return jsonify({'code': 200, 'list': res})
    else:
        time.sleep(1)
        pid = request.args.get('pid')
        sql1 = "select * from role where pid=%d" % (int(pid))
        res1 = db.get_all(sql1)
        return jsonify({'code': 200, 'list': res1})


@bp_user.route('/getusers')
def getusers():
    sql = "select id,username,phone from user"
    res = db.get_all(sql)
    return jsonify({'code':200,'list':res})


# 用装饰器实现level为003在2021-10-01，2022-10-10时间段内内网对某个资源只有读取的权限
import datetime
def timer(func):
    @functools.wraps(func)
    def decor(*args, **kwargs):
        token=request.headers['Token']

        num=myjwt.decode_jwt(token)
        data = rs.get_all_hash('abac')
        ip=request.remote_addr
        times = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")
        for (key, value) in data.items():
            if key == 'ip':
                if str(value)!=str(ip):
                    return 'ip限制'
            if key=='time':
                starttime=eval(value)[0]
                end=eval(value)[1]
                if starttime>times and times>end:
                    return '时间限制'
            if key=='role':
                sql = "select role_id from users where id=%s" % num['data']['uid']
                roleid=db.get_one(sql)
                if roleid['role_id'] !=int(value):
                    return '角色限制'
            if request.method != 'GET':
                return '请求方法限制'
        return  func( *args, **kwargs)
    return decor



@bp_user.route('/roleM',methods=['GET','POST','PUT','DELETE'])

def roleM():

    return 'hhhh'


import time
@bp_user.route('/hash_shu',methods=['GET','POST'])
@timer
def hash_shu():
    rs.insert_hash('abac','ip','127.0.0.1')
    rs.insert_hash('abac','time',"['2020-10-15','2022-1-30']")
    rs.insert_hash('abac','role','1')
    data=rs.get_all_hash('abac')

    times=datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d")
    for (key,value) in data.items():
        if key=='time':
            print(eval(value)[0])
    return 'ok'



@bp_user.route('/worklist')

def worklist():

    sql = "select * from workflow"

    res = db.get_all(sql)

    return jsonify({'code':200,'list':res})
  

#获取数据源接口
@bp_user.route('/getresourcedata',methods={'POST','GET'})      
def getresourcedata():

    if request.method == 'GET':
        #从redis取，如果有直接返回
        values = rs.get_str('dataresouce')

        if values:
            list = eval(values)

        else:
            #如果没有查询
            sql = "select * from data_source"
            res = db.get_all(sql)
            list = []

            if res:
                for i in res:
                    dict={'id':i['id'],'name':i['name']}

                    sql1 = "select id,name,type from %s"%(i['tablename'])

                    subres = db.get_all(sql1)
                    dict['mes'] = subres
                    list.append(dict)
            #存入redis
            rs.set_str('dataresouce',json.dumps(list))
        return jsonify({"code":200,'list':list})     
    else:

        data = request.data
        if data:

            data = json.loads(data)

        else:

            data = request.form

        sql = " update workflow set params = '%s' where id=%d " % (data['mes'],int(data['id']))

        db.update(sql)

        return jsonify({"code":200})

                   
@bp_user.route('/getworkf', methods=['POST', 'GET'])

def getworkf():

    if request.method == 'GET':
        id = request.args.get('id')

        sql = " select * from workflow where id = 1" % int(id)

        res = db.get_one(sql)

        return jsonify({"code":200,"workf":res})